import {baseUrl} from '@/common/baseUrl.js'
export const http = (param) => {
	let url = param.url
	let method = param.method || 'get'
	let header = {}
	let data = param.data || {}
	let token = param.token || ""
	let hideLoading = param.hideLoading || false
	let requestUrl = baseUrl + url
	let Authorization = uni.getStorageSync('logintoken') || '';
	// 判断method
	if (method) {
		method = method.toUpperCase(); //小写改为大写
		header['Accept'] = 'application/json'
		if (method == "POST") {
			header['content-type'] = "application/x-www-form-urlencoded"
		} else {
			header['content-type'] = "application/json"
		}
		if (Authorization) {
			header['Authorization'] = Authorization
		}
	}
	//加载圈
	if (!hideLoading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: requestUrl,
			method: method,
			data: data,
			header: header,
			success: (res) => {
				// console.log(res)
				if (!hideLoading) {
					uni.hideLoading();
				}
				if (res.statusCode && res.statusCode == 401) {
					uni.removeStorageSync('logintoken')
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1000)
					return;
				}
				if (res.statusCode && res.statusCode != 200) {
					uni.showToast({
						title: "api错误" + res.errMsg,
						icon: 'none'
					})
					return;
				}
				// 请求状态200   单返回不等于200 
				if (res.data.code) {
					if (res.data.code != '200') {
						if (res.data.code != 402 && res.data.code != 401) {
							console.log(res.data)
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
						if (res.data.code == 402 || res.data.code == 401) {
							uni.removeStorageSync('logintoken')
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}, 1000)
						}
						return;
					}
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					return;
				}
				// 将结果抛出
				resolve(res.data)
			},
			// 请求失败
			fail: (e) => {
				uni.showToast({
					title: "" + e.data.msg,
					icon: 'none'
				});
				resolve(e.data)
			},
			//请求完成
			complete() {
				resolve();
				return;
			}
		})
	})
}